<template>
  <div class="app-container">
    <h1>轮播图管理</h1>
    <el-button type="primary" @click="addBanner">新增轮播图</el-button>
    <el-table
      :data="bannerList"
      border
      style="width: 100%">
      <el-table-column align="center" label="ID" width="80">
        <template slot-scope="scope">
          {{ scope.$index+1 }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="title"
        label="标题"
        width="130">
      </el-table-column>
      <el-table-column align="center" label="轮播图" width="600">
        <template slot-scope="scope">
          <img :src="scope.row.imageUrl" :alt="scope.row.title" width="100%">
        </template>
      </el-table-column>
      <el-table-column label="链接地址" width="180" align="center">
        <template slot-scope="scope">
          {{ scope.row.linkUrl }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="排序"
        width="130">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.sort }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        width="180">
        <template slot-scope="scope">
          <el-button type="primary" @click="upd(scope.row)">修改</el-button>
          <el-button type="danger" @click="del(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      @current-change="currentChange"
      :page-size="getPages.pageSize"
      :page-count="getPages.pages"
      :total="getPages.total">
    </el-pagination>
    <el-dialog
      title="轮播图新增/修改"
      :visible.sync="dialogVisible"
      @close="dialogClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="80%">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="轮播图标题" prop="title">
          <el-input v-model="ruleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="上传轮播图" prop="file">
          <el-upload
            drag
            ref="upload"
            action="#"
            :show-file-list="false"
            :on-change="changeUpload"
            :auto-upload="false"
            multiple>
            <i v-if="!imageUrl" class="el-icon-upload"></i>
            <img v-if="imageUrl" :src="imageUrl" style="width: 100%;height: 100%;">
          </el-upload>
        </el-form-item>
        <el-form-item label="链接地址" prop="linkUrl">
          <el-input placeholder="请输入内容" v-model="ruleForm.linkUrl">
            <template slot="prepend">https://</template>
          </el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="ruleForm.sort" controls-position="right" :min="1"></el-input-number>
          <span style="color: red">*值越小越靠前*</span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="esc">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import {addOrUpdBanner, deleteBanner, getBanner} from "../../api/banner";
export default {
  name: "save",
  data () {
    return {
      imageUrl:'',
      getPages: {
        pageNum: 1,
        pageSize: 5,
        pages: 0,
        total: 0
      },
      ruleForm: {
        id:'',
        title:'',
        imageUrl:'',
        linkUrl:'',
        sort:'',
        file:''
      },
      rules: {
        title: [
          {required: true, message: '请输入轮播图标题', trigger: 'blur'},
        ],
        file: [
          {required: true, message: '请上传轮播图', trigger: 'blur'},
        ],
        sort: [
          {required: true, message: '请输入排序', trigger: 'blur'},
          {pattern: /^[1-9]\d*$/, message: '必须是正整数', trigger: 'blur'},
        ],
      },
      dialogVisible: false,
      dialogVisibleUrl: false,
      bannerList:[],
      BASE_API:process.env.BASE_API,
      headersObj:{
        'Authorization':'Bearer'+getToken()
      },
      basePath:'http://localhost:9527/upload/banner/'
    }
  },
  created() {
    this.getBannerList()
  },
  methods:{
    del(row) {
      this.$confirm('此操作将删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteBanner(row.id).then(response => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getBannerList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if(valid){
          if (this.ruleForm.linkUrl.trim() != '') {
            this.ruleForm.linkUrl='https://'+this.ruleForm.linkUrl
          }
          var formData = new FormData
          var data = this.ruleForm;
          for (let key in data){
            formData.append(key,data[key])
          }
          addOrUpdBanner(formData).then(res => {
            if (res.code == 20000) {
              this.dialogVisible = false
              // this.$refs.upload.clearFiles()
              this.ruleForm = {}
              this.getBannerList()
              this.$message.success("操作成功")
            }else {
              this.$message.error("操作失败")
            }
          })
        }
      })
    },
    esc() {
      this.dialogVisible = false
      // this.$refs.upload.clearFiles()
      this.ruleForm = {}
      this.getBannerList()
    },
    currentChange(num) {
      this.getPages.pageNum = num
      this.getBannerList()
    },
    getBannerList() {
      getBanner(this.getPages).then(res => {
        this.bannerList = res.data.records
        this.getPages.total = res.data.total
        this.getPages.pageNum = res.data.currency
        this.getPages.pages = res.data.pages
      })
    },
    changeUpload(file) {
      this.ruleForm.file = file.raw;
      this.imageUrl = URL.createObjectURL(file.raw)
      this.$refs.ruleForm.clearValidate(['file'])
      this.rules['file'] = null
    },
    dialogClose() {
      this.$refs.ruleForm.resetFields();
      this.ruleForm={}
    },
    addBanner() {
      this.imageUrl = ''
      this.rules['file'] = [
        {required: true, message: '请上传轮播图',trigger: 'blur'}
      ]
      this.dialogVisible = true
    },
    upd(ban){
      this.ruleForm.id = ban.id
      this.ruleForm.title = ban.title
      this.ruleForm.imageUrl = ban.imageUrl
      this.ruleForm.linkUrl = ban.linkUrl
      this.ruleForm.sort = ban.sort
      this.imageUrl = ban.imageUrl
      this.dialogVisible = true
      this.rules['file'] = null
    }
  }
}
</script>

<style scoped>

</style>
